package io.sage.modules.integral.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.sage.modules.integral.dao.GIntegralListMapper;
import io.sage.modules.integral.entity.GIntegralDetail;
import io.sage.modules.integral.entity.GIntegralList;
import io.sage.modules.integral.enums.IntegralAddOrDelType;
import io.sage.modules.integral.enums.IntegralType;
import io.sage.modules.integral.service.GIntegralDetailService;
import io.sage.modules.integral.service.GIntegralListService;

@Service("gIntegralListService")
public class GIntegralListServiceImpl implements GIntegralListService {
	
	@Autowired
	private GIntegralListMapper integralListMapper;
	
	@Autowired
	private GIntegralDetailService integralDetailService;
	
	@Override
	public List<GIntegralList> selectIntegralList(Map<String, Object> params) {
		
		return integralListMapper.selectIntegralList(params);
	}

	@Override
	public GIntegralList selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return integralListMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(GIntegralList integralList) {
		
		GIntegralList integralList1 = integralListMapper.selectByPrimaryKey(integralList.getId());
		BigDecimal integralSumh = new BigDecimal(integralList1.getIntegralSum());
		BigDecimal integralSumh1 = new BigDecimal(integralList.getIntegralSum());
		BigDecimal subtract = integralSumh.subtract(integralSumh1);
		
		GIntegralDetail integralDetail=new GIntegralDetail();
		integralDetail.setDisFlag(0);
		integralDetail.setIntegralType(IntegralType.SYSTEM.getCode());
		integralDetail.setIntegral(Math.abs(subtract.intValue())+"");
		integralDetail.setStudentId(integralList.getStudentId());
		integralDetail.setUpdateTime(new Date());
		integralDetail.setCreateTime(new Date());

		//如果大于零  说明是减少积分操作
		if(subtract.intValue()>0){
			integralDetail.setOperationType(IntegralAddOrDelType.SUBTRACT_INTEGRAL.getCode());
		}else {
			integralDetail.setOperationType(IntegralAddOrDelType.ADD_INTEGRAL.getCode());
		}
		
		int integralDetailOperation = integralDetailService.insertSelective(integralDetail);
		
		if(integralDetailOperation<0){
			return -1;
		}
		
		return integralListMapper.updateByPrimaryKeySelective(integralList);
	}

	@Override
	public GIntegralList selectByStudentId(Integer studentId) {
		// TODO Auto-generated method stub
		return integralListMapper.selectByStudentId(studentId);
	}

	@Override
	public int saveIntegralList(GIntegralList record) {
		record.setCreateTime(new Date());
		record.setUpdateTime(new Date());
		return integralListMapper.insertSelective(record);
	}

	@Override
	public int updateByStudentId(GIntegralList record) {
		// TODO Auto-generated method stub
		return integralListMapper.updateByStudentId(record);
	}

}
